#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
#include "lcd.h"

#define ASC_SIZE    16
#define ASC_LEN     4096
char asc_buf[ASC_LEN];
static int asc_ok = 0;

#define HZK_SIZE   32
#define HZK_LEN    267616
char hzk_buf[HZK_LEN];
static int hzk_ok = 0;

#define show_char(p, width, height)\
{\
  int i, j;\
\
  for (i = 0; i < (height); i++){		\
    for (j = 0; j < (width); j++){		\
      char b = *(p + ((width)/8)*i + j/8);	\
      if (b & (1<<(7-j%8)))\
	fb_PutPixel(x+j, y+i, color);\
    }\
  }\
}

static void fb_CacheASC(void)
{
  FILE *fp;
  int r;

  fp = fopen("ASC16", "rb");
  if (fp == NULL){
    fprintf(stderr, "Fail to open ASC16.\n");
    return;
  }
  fread(asc_buf, ASC_LEN, 1, fp);
  fclose(fp);
}

void fb_DrawASC(int x, int y, int asc, int color)
{
  char *p = asc_buf + asc*16;
  int i, j;

  if (!asc_ok){
    fb_CacheASC();
    asc_ok = 1;
  }

  show_char(p, 8, 16);
}

static int code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int outlen)
{
  iconv_t cd;
  int rc;
  char **pin = &inbuf;
  char **pout = &outbuf;

  cd = iconv_open(to_charset,from_charset);
  if (cd==0) return -1;
  memset(outbuf,0,outlen);
  if (iconv(cd,pin,&inlen,pout,&outlen)==-1) 
    return -1;
  iconv_close(cd);
  return 0;
}

int u2g(char *inbuf, int inlen, char *outbuf, int outlen)
{
  return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
}

int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
  return code_convert("gb2312", "utf-8", inbuf, inlen,outbuf, outlen);
}

static void fb_CacheHZK(void)
{
  FILE *fp;
  int r;

  fp = fopen("HZK16", "rb");
  if (fp == NULL){
    fprintf(stderr, "Fail to open HZK16.\n");
    return;
  }
  fread(hzk_buf, HZK_LEN, 1, fp);
  fclose(fp);
}

void fb_DrawHZK(int x, int y, int hzk, int color)
{
  char *p;
  unsigned short qh, wh;
  int i, j;

  if (!hzk_ok){
    fb_CacheHZK();
    hzk_ok = 1;
  }

  wh = ((hzk >> 8) & 0xff) - 0xa0;
  qh = hzk & 0x00ff - 0xa0;
  p = hzk_buf + ((qh-1)*94+wh-1)*32;
  show_char(p,16, 16);
}


